<template>
  <view class="feedback-container" @click="closeAllItems">
    <!-- 顶部导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="navigateBack">
        <FeatherIcon name="chevron-left" size="24" color="#333"></FeatherIcon>
      </view>
      <text class="navbar-title">问题反馈</text>
      <view class="navbar-right"></view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="isLoading">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="feedbackList.length === 0">
      <FeatherIcon name="message-square" size="80" color="#ddd"></FeatherIcon>
      <text class="empty-text">您还没有提交过反馈</text>
      <text class="empty-desc">有任何问题或建议，欢迎向我们反馈</text>
      <button class="primary-btn" @click="navigateToAddFeedback">
        我要反馈
      </button>
    </view>

    <!-- 反馈列表 -->
    <view class="feedback-list" v-else>
      <view
        class="feedback-item-wrapper"
        v-for="(item, index) in feedbackList"
        :key="index"
        @touchstart="handleTouchStart($event, index)"
        @touchmove="handleTouchMove($event, index)"
        @touchend="handleTouchEnd($event, index)"
      >
        <!-- 卡片内容 -->
        <view
          class="feedback-item"
          :style="{ transform: `translateX(${item.x}px)` }"
        >
          <view
            class="feedback-content-wrapper"
            @tap.stop="navigateToDetail(item._id)"
          >
            <view class="feedback-header">
              <text class="feedback-title">{{ item.title }}</text>
              <view :class="['status-tag', getStatusClass(item.status)]">{{
                getStatusText(item.status)
              }}</view>
            </view>
            <text class="feedback-content">{{ item.content }}</text>
            <view class="feedback-footer">
              <text class="feedback-time">{{
                formatTime(item.createdAt)
              }}</text>
              <view
                class="feedback-replies"
                v-if="item.replies && item.replies.length > 0"
              >
                <FeatherIcon
                  name="message-circle"
                  size="14"
                  color="#999"
                ></FeatherIcon>
                <text class="reply-count">{{ item.replies.length }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 删除按钮 -->
        <view class="delete-btn" @tap.stop="showDeleteConfirm(item._id)">
          <FeatherIcon name="trash-2" size="24" color="#fff"></FeatherIcon>
          <text class="delete-text">删除</text>
        </view>
      </view>
    </view>

    <!-- 底部添加按钮 -->
    <view
      class="add-feedback-btn"
      v-if="feedbackList.length > 0"
      @click="navigateToAddFeedback"
    >
      <FeatherIcon name="plus" size="24" color="#fff"></FeatherIcon>
    </view>

    <!-- 删除确认弹窗 -->
    <view class="delete-confirm-modal" v-if="deleteModalVisible">
      <view class="delete-confirm-content">
        <text class="delete-confirm-title">确认删除</text>
        <text class="delete-confirm-desc"
          >删除后无法恢复，确定要删除该反馈吗？</text
        >
        <view class="delete-confirm-btns">
          <button class="cancel-btn" @click="cancelDelete">取消</button>
          <button class="confirm-btn" @click="confirmDelete">删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import {
  showLoading,
  hideLoading,
  showSuccess,
  showError,
} from "@/utils/common";
import { getFeedbackList, deleteFeedback } from "@/api";
import { isLoggedIn } from "@/api";
import { onShow, onHide } from "@dcloudio/uni-app";

// 反馈列表数据
const feedbackList = ref([]);
// 加载状态
const isLoading = ref(true);
// 用户信息
const userInfo = ref(null);
// 删除确认弹窗显示状态
const deleteModalVisible = ref(false);
// 要删除的反馈ID
const feedbackToDelete = ref("");
// 删除按钮宽度
const DELETE_BTN_WIDTH = 160;
// 左滑阈值
const SWIPE_THRESHOLD = 50;

// 在movable-view之前添加另一种实现
const touchStartX = ref(0);
const touchStartY = ref(0);
const isMoving = ref(false);

// 获取用户信息从缓存
const getUserInfoFromStorage = () => {
  try {
    const userInfoStr = uni.getStorageSync("userInfo");
    if (userInfoStr) {
      userInfo.value = JSON.parse(userInfoStr);
    }
  } catch (e) {
    console.error("获取用户信息失败:", e);
  }
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 获取反馈列表
const fetchFeedbackList = async () => {
  if (!isLoggedIn()) {
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return;
  }

  isLoading.value = true;
  try {
    getUserInfoFromStorage();

    // 获取当前用户ID
    const userId = userInfo.value?.oId || "";

    if (!userId) {
      showError("获取用户信息失败");
      isLoading.value = false;
      return;
    }

    console.log("获取反馈列表，用户ID:", userId);
    const res = await getFeedbackList({ userId });
    console.log("获取反馈列表，res:", res);

    if (res && res.data) {
      // 确保只显示当前用户的反馈
      const list = Array.isArray(res.data)
        ? res.data.filter((item) => item && item.userId === userId)
        : [];
      // 添加左滑所需属性
      feedbackList.value = list.map((item) => ({
        ...item,
        x: 0,
      }));
      console.log("过滤后的反馈数量:", feedbackList.value.length);
    } else {
      feedbackList.value = [];
    }
  } catch (error) {
    console.error("获取反馈列表失败:", error);
    showError("获取反馈列表失败，请稍后重试");
    feedbackList.value = [];
  } finally {
    isLoading.value = false;
  }
};

// 左滑处理
const onItemMove = (e, index) => {
  console.log("滑动事件触发:", JSON.stringify(e.detail), "索引:", index);

  const { x } = e.detail;
  feedbackList.value[index].x = x;

  // 如果超过阈值，则展开删除按钮
  if (x < -SWIPE_THRESHOLD) {
    console.log("自动展开删除按钮");
    setTimeout(() => {
      feedbackList.value[index].x = -DELETE_BTN_WIDTH;
    }, 0);
  } else if (x > -10 && x < 0) {
    // 如果很接近0，则自动复位
    console.log("自动复位");
    setTimeout(() => {
      feedbackList.value[index].x = 0;
    }, 0);
  }
};

// 触摸处理函数
const handleTouchStart = (e, index) => {
  touchStartX.value = e.touches[0].clientX;
  touchStartY.value = e.touches[0].clientY;
  isMoving.value = true;

  // 关闭其他已打开的项
  feedbackList.value.forEach((item, idx) => {
    if (idx !== index && item.x < 0) {
      feedbackList.value[idx].x = 0;
    }
  });
};

const handleTouchMove = (e, index) => {
  if (!isMoving.value) return;

  // 计算水平滑动距离
  const moveX = e.touches[0].clientX - touchStartX.value;
  const moveY = e.touches[0].clientY - touchStartY.value;

  // 仅处理水平滑动
  if (Math.abs(moveX) > Math.abs(moveY)) {
    // 只允许向左滑动（负值）
    if (moveX <= 0) {
      // 限制最大滑动距离
      const x = Math.max(moveX, -DELETE_BTN_WIDTH);
      feedbackList.value[index].x = x;
    } else if (feedbackList.value[index].x < 0) {
      // 如果是向右滑动且当前已经有左滑状态，允许恢复
      const x = Math.min(0, feedbackList.value[index].x + Math.abs(moveX / 2));
      feedbackList.value[index].x = x;
    }
  }
};

const handleTouchEnd = (e, index) => {
  isMoving.value = false;

  // 获取当前x值
  const x = feedbackList.value[index].x;

  // 根据阈值决定是否展开或收起
  if (x < -SWIPE_THRESHOLD) {
    feedbackList.value[index].x = -DELETE_BTN_WIDTH;
  } else {
    feedbackList.value[index].x = 0;
  }
};

// 当点击任何地方时关闭所有打开的滑动项
const closeAllItems = () => {
  feedbackList.value.forEach((item, index) => {
    if (item.x < 0) {
      feedbackList.value[index].x = 0;
    }
  });
};

// 跳转到添加反馈页面
const navigateToAddFeedback = () => {
  uni.navigateTo({
    url: "/pages/feedback/add-feedback",
  });
};

// 跳转到反馈详情页面
const navigateToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/feedback/feedback-detail?id=${id}`,
  });
};

// 显示删除确认弹窗
const showDeleteConfirm = (id) => {
  feedbackToDelete.value = id;
  deleteModalVisible.value = true;
};

// 取消删除
const cancelDelete = () => {
  deleteModalVisible.value = false;
  feedbackToDelete.value = "";
};

// 确认删除
const confirmDelete = async () => {
  if (!feedbackToDelete.value) return;

  showLoading("删除中");
  try {
    const res = await deleteFeedback(feedbackToDelete.value);
    if (res && res.message) {
      showSuccess("删除成功");
      // 从列表中移除已删除的反馈
      feedbackList.value = feedbackList.value.filter(
        (item) => item._id !== feedbackToDelete.value
      );
    } else {
      showError("删除失败");
    }
  } catch (error) {
    console.error("删除反馈失败:", error);
    showError("删除失败，请稍后重试");
  } finally {
    hideLoading();
    deleteModalVisible.value = false;
    feedbackToDelete.value = "";
  }
};

// 获取状态文字
const getStatusText = (status) => {
  const statusMap = {
    pending: "待处理",
    processing: "处理中",
    resolved: "已解决",
    closed: "已关闭",
  };
  return statusMap[status] || "待处理";
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    pending: "status-pending",
    processing: "status-processing",
    resolved: "status-resolved",
    closed: "status-closed",
  };
  return classMap[status] || "status-pending";
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return "";

  const date = new Date(timeStr);
  const now = new Date();
  const diff = now - date;

  // 一小时内
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000);
    return `${minutes ? minutes : "几"}分钟前`;
  }

  // 一天内
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000);
    return `${hours}小时前`;
  }

  // 一周内
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000);
    return `${days}天前`;
  }

  // 其他
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

onMounted(() => {
  fetchFeedbackList();
});

// 每次页面显示时都刷新数据
onShow(() => {
  // 检查是否有需要刷新的标记
  const needRefresh = uni.getStorageSync("feedback_list_need_refresh");

  if (needRefresh === "true" || !feedbackList.value.length) {
    // 清除刷新标记
    uni.removeStorageSync("feedback_list_need_refresh");

    if (isLoggedIn()) {
      fetchFeedbackList();
    }
  }
});
</script>

<style lang="scss">
.feedback-container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  padding-top: 80rpx;
  padding-bottom: 20rpx;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  z-index: 999;
  display: flex;
  align-items: center;

  .navbar-left {
    width: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .navbar-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .navbar-right {
    width: 90rpx;
  }
}

.loading-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;

  .loading-spinner {
    width: 50rpx;
    height: 50rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #ff9800;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 50rpx 0;

  .empty-text {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-top: 30rpx;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 50rpx;
    text-align: center;
  }

  .primary-btn {
    width: 70%;
    height: 90rpx;
    line-height: 90rpx;
    background: linear-gradient(135deg, #ff9800, #ff5722);
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
    box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
    border: none;

    &:after {
      border: none;
    }
  }
}

.feedback-list {
  padding: 180rpx 30rpx 30rpx;

  .feedback-item-wrapper {
    margin-bottom: 24rpx;
    height: 220rpx; /* 设置固定高度，与内容高度匹配 */
    position: relative;
    overflow: hidden;
    border-radius: 16rpx;
    background-color: #ff5252; /* 底层背景色为删除按钮颜色 */
  }

  .feedback-item {
    background-color: #fff;
    width: 100%;
    height: 100%;
    position: relative;
    z-index: 2;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: transform 0.2s ease; /* 平滑过渡效果 */

    .feedback-content-wrapper {
      padding: 30rpx;
      height: 100%;
      box-sizing: border-box;
    }

    .feedback-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;

      .feedback-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        flex: 1;
      }

      .status-tag {
        font-size: 22rpx;
        padding: 6rpx 16rpx;
        border-radius: 20rpx;

        &.status-pending {
          background-color: rgba(255, 152, 0, 0.1);
          color: #ff9800;
        }

        &.status-processing {
          background-color: rgba(33, 150, 243, 0.1);
          color: #2196f3;
        }

        &.status-resolved {
          background-color: rgba(76, 175, 80, 0.1);
          color: #4caf50;
        }

        &.status-closed {
          background-color: rgba(158, 158, 158, 0.1);
          color: #9e9e9e;
        }
      }
    }

    .feedback-content {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      line-height: 1.5;
    }

    .feedback-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .feedback-time {
        font-size: 24rpx;
        color: #999;
      }

      .feedback-replies {
        display: flex;
        align-items: center;

        .reply-count {
          font-size: 24rpx;
          color: #999;
          margin-left: 6rpx;
        }
      }
    }
  }

  .delete-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 160rpx;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 1;

    .delete-text {
      font-size: 26rpx;
      color: #fff;
      margin-top: 8rpx;
    }
  }
}

.add-feedback-btn {
  position: fixed;
  right: 40rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(255, 87, 34, 0.3);
  z-index: 99;
}

.delete-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;

  .delete-confirm-content {
    width: 80%;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 40rpx 30rpx;

    .delete-confirm-title {
      font-size: 34rpx;
      font-weight: 600;
      color: #333;
      text-align: center;
      margin-bottom: 30rpx;
      display: block;
    }

    .delete-confirm-desc {
      font-size: 28rpx;
      color: #666;
      text-align: center;
      margin-bottom: 40rpx;
      display: block;
    }

    .delete-confirm-btns {
      display: flex;
      justify-content: space-between;

      button {
        flex: 1;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 30rpx;
        border-radius: 40rpx;
        margin: 0 20rpx;

        &:after {
          border: none;
        }
      }

      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }

      .confirm-btn {
        background-color: #ff5252;
        color: #fff;
      }
    }
  }
}
</style>
